<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-in', title: '入库信息' },
          { name: 'box-dtl', title: '入库明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly"  :label-width="100">
        <template #content>
          <customFormItem
            label="扫码入库"
            name="scanInfo"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
            fullWidth
            style="width: 100px;font-size: 20px;"
            v-show="(cpIsAsn || cpIsPackage) && cpIsNew"
          >
            <template #content>
              <FortenScan
                          ref="scanInput"
                          propPlaceholder="扫码或者输入送货单号后，回车确认"
                          @after-scan="barCodeScanMain"
                          propType="codeOther"
                          style="width: 350px;"/>
            </template>
          </customFormItem>

          <div id="box-in" class="box-title">入库信息</div>

          <customFormItem label="入库分类" name="purchaseOrderType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.baseMatrType}"
                          :disabled="!cpIsNew || cpIsAsn"
                          help-tip="不同分类的属性选项是不一样的<br>保存后不可修改"
                          @change="fetchChildData"
                          ref="purchaseOrderType"
          />

          <customFormItem
            label="入库仓库" name="warehouseName" :parent="_self" :form="form"
            help="保存后不可修改"
            @focusTo="$refs.warehouseName.focus()"
            :type="constCommon.formItemType.slot.name"
            :disabled="!cpIsNew"
          >
            <template #content>
              <warehouseSelect
                :flagCenter="true"
                v-model="form.warehouseId"
                :valueDisplay="form.warehouseName"
                @change="warehouseChange"
                :disabled="!cpIsNew"
                ref="warehouseName"
              />
            </template>
          </customFormItem>

          <customFormItem
            label="入库日期" name="busDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
          />

          <customFormItem
            label="需求科室" name="deptName" :parent="_self" :form="form"
            help-tip="该入库的原始需求科室<br>指定后审核通过可以一键转出库"
            @focusTo="$refs.deptName.focus()"
            :type="constCommon.formItemType.slot.name"
            :disabled="cpIsAsn"
          >
            <template #content>
              <deptSelect
                v-model="form.deptId"
                :valueDisplay="form.deptName"
                @change="deptChange"
                :disabled="cpIsAsn || propReadonly"
                ref="deptName"
              />
            </template>
          </customFormItem>


<!--          <customFormItem
            label="入库类型" name="busType" :parent="_self" :form="form"
            :type="constCommon.formItemType.selectDict.name"
            :config="{ dictType: constCommon.dictType.wmInOrderType }"
            disabled
          />-->

          <customFormItem
            label="供应商" name="supplierName" :parent="_self" :form="form"
            help-tip="保存后不可修改"
            @focusTo="$refs.supplierName.focus()"
            :type="constCommon.formItemType.slot.name"
            :disabled="!cpIsNew || cpIsAsn || cpIsInit"
          >
            <template #content>
              <spSelect
                v-model="form.supplierId"
                :valueDisplay="form.supplierName"
                @change="supplierChange"
                :disabled="!cpIsNew || cpIsAsn || cpIsInit"
                ref="supplierName"
              />
            </template>
          </customFormItem>


          <customFormItem
            label="入库单号" name="busKey" :parent="_self" :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            :config="{ value: form.busKey }"
          />
          <customFormItem
            label="入库人" name="busUser" :parent="_self" :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            :config="{ value: form.busUser }"
          />

          <customFormItem
            label="入库金额"
            name="amount"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            :config="{ value: form.amount }"
          />

          <!--医疗用品专属属性-->
          <template v-if="utils.isBaseTypeMed(form.purchaseOrderType)">
            <customFormItem
              label="采购订单" name="refKey" :parent="_self" :form="form"
              :readonly="true"
              :showSelectIcon="true"
              @focus="utilSelect.purchaseOrder(purchaseOrderSelect)"
              :disabled="!cpIsNew || cpIsAsn"
              help-tip="保存后不可修改,选择后将填充表单的相关属性"
              v-show="!cpIsInit && !cpIsPackage"
            />

            <customFormItem label="是否寄售" name="flagConsignment" :parent="_self" :form="form"
                            :disabled="!cpIsNew || cpIsAsn"
                            help="保存后不可修改"
                            :type="constCommon.formItemType.radio.name"
                            :config="{options: constCommon.nobusConst.yesNoBoolean}"
            />
            <customFormItem label="标签管理" name="flagOmoc" :parent="_self" :form="form"
                            :disabled="!cpIsNew || cpIsAsn"
                            help="保存后不可修改"
                            :type="constCommon.formItemType.radio.name"
                            :config="{options: constCommon.nobusConst.yesNoBoolean}"
            />
            <customFormItem
              label="送货单"
              name="asnKey"
              :parent="_self"
              :form="form"
              :disabled="cpIsAsn"
            />
            <customFormItem
              label="送货人"
              name="deliveryman"
              :parent="_self"
              :form="form"
            />
            <customFormItem
              label="发票号"
              name="invoiceNo"
              :parent="_self"
              :form="form"
            />
            <customFormItem label="到货温度" name="arrivalTemperature" :parent="_self" :form="form"
                            :type="constCommon.formItemType.inputNumber.name"
                            v-show="cpIsReagent"
            />
          </template>

          <customFormItem
            label="备注"
            name="remark"
            :parent="_self"
            :form="form"
            width2x
          />

          <customFormItem
            label="送货附件"
            name="matrImg"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
            width2x
          >
            <template #content>
              <customUpload
                :data="{ fileRefId: form.id, fileRefTable: 'purchase_order', fileSavePath: 'purchase_order'}"
                :hide="cpIsNew"
                hideMsg="请先保存主单据后再上传"
                :max="20"
                :disabled="propReadonly"
                multiple
              />
            </template>
          </customFormItem>

        </template>
      </customForm>

      <div id="box-dtl" class="box-title" style="margin-top: 10px">入库明细</div>
      <customTooltip title="title" v-show="!propReadonly && !this.cpIsAsn && !this.cpIsPackage">
        <template #title>
          <div>
            1、支持UDI/GTIN解析<br>
            2、可以长主码解析，也可以主码加副码解析，副码可以任意顺序<br>
            3、GS1格式 (01)产品标识DI (11)生产日期 (17)失效日期 (10)生产批号 (21)序列号
          </div>
          <div>
            UDI编码(01)06901234567892(17)250505(11)220202(10)lot123(21)sn0001
          </div>
          <div>
            UDI编码(01)06 9012345 67893(17) 250505 (11)220202(10)lot123(21)sn0001
          </div>
        </template>
        <template #content>
          <FortenScan
            ref="scanInputMain"
            propMsgPrepend="主码"
            propPlaceholder="请扫描"
            propType="custom"
            :propClearAfterScan="false"
            :propEnterHandel="false"
            @after-scan="scanInputMainAfterScan"
            style="width: 450px;margin-top: 10px;display: inline-block;"/>
          <FortenScan
            ref="scanInputSub"
            propMsgPrepend="副码"
            propPlaceholder="请扫描"
            :propClearAfterScan="false"
            :propEnterHandel="false"
            :propAutofocus="false"
            propType="custom"
            style="width: 400px;margin-top: 10px;display: inline-block;margin-left: 10px; margin-right: 10px;"/>
          <customButton  title="确认"  class="btn-scan" theme="primary" size="medium" @click="barCodeScanInputConfirm"/>
        </template>
      </customTooltip>

      <!--入库明细 标准-->
      <data-view
        propViewKey="wm_in_order_item_inasn"
        propViewForm="wm/in-order-item/detail.vue"
        :propInitData="form"
        ref="childDataView"
        :propParentPage="_self"
        :propAutoFetchData="false"
        :propParentData="propParent.viewFormData"
        @after-load="afterLoad"
        @edit-input="rowEditInput"
        @extra-button-click="extraButtonClick"
        :propFlowKey="propParent.propFlowKey"
        :propNoEditRow="true"
        @customSelectFocus="customSelectFocus"
        :propHideFlowSelect="true"
        :propFilterBtn="propFilterBtn"
        :propIsColumnEdit="propIsColumnEdit"
        :propBeforeClick="propBeforeClickDtl"
        :propTableHide="propParent.cpFormNew && cpIsPackage"
        propTableHideMsg="请先保存主单据再操作"
        :propChildTableStyle="{marginLeft: '280px'}"
        v-show="cpHasMfgInfo"
      />

      <!--入库明细 不含生产信息-->
      <data-view
        propViewKey="wm_in_order_item_inasn_nomfg"
        propViewForm="wm/in-order-item/detail.vue"
        :propInitData="form"
        ref="childDataViewNotMfg"
        :propParentPage="_self"
        :propAutoFetchData="false"
        :propParentData="propParent.viewFormData"
        @after-load="afterLoad"
        @edit-input="rowEditInput"
        @extra-button-click="extraButtonClick"
        :propFlowKey="propParent.propFlowKey"
        :propNoEditRow="true"
        @customSelectFocus="customSelectFocus"
        :propHideFlowSelect="true"
        :propFilterBtn="propFilterBtn"
        :propBeforeClick="propBeforeClickDtl"
        :propTableHide="propParent.cpFormNew && cpIsPackage"
        propTableHideMsg="请先保存主单据再操作"
        :propChildTableStyle="{marginLeft: '280px'}"
        v-show="!cpHasMfgInfo"
        :rowEditInputValid="rowEditInputValid"
      />
    </div>



        <!--发货明细导入-->
    <customDrawer title="入库明细导入" ref="customDrawerSgImportDtl" :widthPx="500" :heightPx="500"  hideConfirm>
      <template #content>
          <dataImportArea :config="cpAreaConfig" @success="importSuccess"/>
      </template>
    </customDrawer>


    <!--编辑UDI-->
    <customDrawer
      :autoHide="false"
      :footer="false"
      title="编辑UDI"
      placement="right"
      ref="customDrawerUdi"
    >
      <template #content>
        <editUdi
          :propWorkOrderItemIdRequired="true"
          ref="editUdi"
        />
      </template>
    </customDrawer>

    <!--转出库单确认框-->
    <customDrawer title="出库确认" ref="customDrawerToTransfer" :widthPx="500" :heightPx="250"
                  @confirm="customDrawerToTransferConfirm">
      <template #content>
        <customForm ref="dataConfirm" :data="dataConfirm" :rules="dataConfirmRules">
          <template #content>
            <customFormItem
              label="出库仓库" name="warehouseNameFrom" :parent="_self" :form="dataConfirm"
              :readonly="true" disabled fullWidth
            />

            <customFormItem
              label="收货科室" name="deptNameTo" :parent="_self" :form="dataConfirm"
              @focusTo="$refs.deptNameTo.focus()"
              :type="constCommon.formItemType.slot.name"
              fullWidth
            >
              <template #content>
                <deptSelect
                  v-model="dataConfirm.deptIdTo"
                  :valueDisplay="dataConfirm.deptNameTo"
                  @change="deptNameToSelect"
                  ref="deptNameTo"
                />
              </template>
            </customFormItem>
          </template>
        </customForm>
      </template>
    </customDrawer>

    <!--UDI扫描结果确认框-->
    <customDrawer title="扫码结果确认" ref="customDrawerScan" :widthPx="800" :heightPx="500"
                  @confirm="customDrawerScanConfirm">
      <template #content>
        <customForm ref="scanConfirm" :data="scanConfirm">
          <template #content>
            <customFormItem
              label="UDI" name="udi" :parent="_self" :form="scanConfirm"
              fullWidth
              disabled
            />
            <customFormItem
              label="GTIN" name="gtin" :parent="_self" :form="scanConfirm" disabled
            />
            <customFormItem
              label="UDI-DI" name="udiDi" :parent="_self" :form="scanConfirm" disabled
            />
            <customFormItem
              label="商品名称" name="name" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.staticHtml.name"
              :config="{ value: scanConfirm.name }"
            />
            <customFormItem
              label="商品编码" name="hrpCode" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.staticHtml.name"
              :config="{ value: scanConfirm.hrpCode }"
            />
            <customFormItem
              label="商品规格" name="spec" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.staticHtml.name"
              :config="{ value: scanConfirm.spec }"
            />
            <customFormItem
              label="商品码" name="gtin" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.staticHtml.name"
              :config="{ value: scanConfirm.gtin }"
            />
            <customFormItem
              label="单品单位" name="skuUnit" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.staticHtml.name"
              :config="{ value: scanConfirm.skuUnit }"
            />

            <customFormItem
              label="单品价格" name="skuPrice" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.staticHtml.name"
              :config="{ value: scanConfirm.skuPrice }"
            />

            <customFormItem
              label="供应商" name="supplierName" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.staticHtml.name"
              :config="{ value: scanConfirm.spec }"
              fullWidth
            />
            <customFormItem
              label="生产厂商" name="mfgName" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.staticHtml.name"
              :config="{ value: scanConfirm.mfgName }"
              fullWidth
            />
            <customFormItem
              label="效期" name="expDate" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.datePicker.name"
            />
            <customFormItem
              label="生产日期" name="mfgDate" :parent="_self" :form="scanConfirm"
              :type="constCommon.formItemType.datePicker.name"
            />
            <customFormItem
              label="批次" name="lot" :parent="_self" :form="scanConfirm"
            />
            <customFormItem
              label="厂家序列" name="mfgSn" :parent="_self" :form="scanConfirm"
            />
          </template>
        </customForm>
      </template>
    </customDrawer>

    <!--包选择-->
    <tableDrawerPackOperBag :supplierId="form.supplierId" :deptId="form.deptId" ref="tableDrawerPackOperBag" @confirm="packSelect"/>
  </div>
</template>

<script>
  import barcodeParse from '@/util/barcodeParse.js'
  import editUdi from '@/views/wm/order-barcode/index.vue'
  import customUpload from '@/components/custom/form/customUpload.vue'
  import customAnchor from '@/components/custom/form/customAnchor.vue'
  import tableDrawerPackOperBag from '@/components/custom/bus/tableDrawerPackOperBag.vue'
  import inOrderBarcode from '@/views/wm/order-barcode/stock-common.vue'
  import dataImportArea from '@/views/base/help/dataImportArea.vue'
  import warehouseSelect from '@/components/custom/bus/select/warehouseSelect.vue'
  import deptSelect from '@/components/custom/bus/select/deptSelect.vue'
  import spSelect from '@/components/custom/bus/select/spSelect.vue'

  export default {
    data() {
      return {
        form: {},
        viewData: {},
        dataConfirm: {},
        scanConfirm: {},
        dataConfirmRules: {
          deptNameTo: [
            {required: true, message: '请选择收货科室', type: 'error'},
          ],
          reagentTeamName: [
            {required: true, message: '请选择试剂组', type: 'error'},
          ]
        },
      }
    },

    computed: {
      // 是否是试剂
      cpIsReagent() {
        return this.form.purchaseOrderType && this.form.purchaseOrderType == 'reagent'
      },
      // 是否未保存的数据
      cpIsNew() {
        return this.strings.isBlank(this.form.id)
      },
      // 是否是采购入库
      cpIsAsn() {
        return this.constCommon.dictType.wmInOrderTypeInAsn == this.propParam.busType
      },
      // 是否是期初入库
      cpIsInit() {
        return this.constCommon.dictType.wmInOrderTypeInInit == this.propParam.busType
      },
      // 是否是跟台入库
      cpIsPackage() {
        return this.constCommon.dictType.wmInOrderTypeInPackage == this.propParam.busType || this.constCommon.dictType.wmInOrderTypeInPackage == this.form.busType
      },
      // 列表视图标识
      cpHasMfgInfo() {
        if (this.utils.isBaseTypeLom(this.form.purchaseOrderType)) {
          return  false
        }
        return  true
      },
    },
    created() {
      let that = this
      this.$emit('event-register', {
        validate: callback => {
          return this.$refs.editForm.validate(callback)
        },
        beforeSave: () => {
          this.$emit('data-callback', this.form)

          if (this.strings.isBlank(this.form.flagConsignment)) {
            this.$set(this.form, 'flagConsignment', false)
          }
          if (this.strings.isBlank(this.form.flagOmoc)) {
            this.$set(this.form, 'flagOmoc', false)
          }
          return true
        },
        afterMove: (formData, initData) => {
          this.form = global.utils.jsonClone(formData)
          if (!formData.id) {
            let getCurrentWarehouse = this.utils.getCurrentWarehouse()

            if (getCurrentWarehouse.warehouseId) {
              if (getCurrentWarehouse.flagCenter) {
                this.$set(this.form, 'warehouseId', this.utils.getCurrentWarehouse().warehouseId)
                this.$set(this.form, 'warehouseName', this.utils.getCurrentWarehouse().warehouseName)
              }
            }

            this.$refs.scanInput.focus()
            this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
            if (!this.cpIsAsn) {
              this.$set(this.form, 'deptId', this.utils.getCurrentUser().deptId)
              this.$set(this.form, 'deptName', this.utils.getCurrentUser().deptName)
            }

            this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDatePattern))
            this.$set(this.form, 'busType', this.propParam.busType)
            this.$set(this.form, 'busKey', '自动获取')
            this.$set(this.form, 'amount', 0)
            // 期初入库
            if (this.cpIsInit) {
              this.$set(this.form, 'supplierName', '自动设置')
            }
            // 采购入库
            if (this.cpIsAsn) {
              this.$set(this.form, 'purchaseOrderType', '自动获取')
              this.$set(this.form, 'supplierName', '自动获取')
              this.$set(this.form, 'flagConsignment', '自动获取')
              this.$set(this.form, 'flagOmoc', '自动获取')
              this.$set(this.form, 'asnKey', '自动获取')
              this.$set(this.form, 'refKey', '自动获取')
              this.$set(this.form, 'deptName', '自动获取')
            } else {
              // this.$set(this.form, 'flagConsignment', true)
              // this.$set(this.form, 'flagOmoc', true)
            }
            this.$nextTick(() => {
              this.$refs.purchaseOrderType.focus()
            })
          }
          this.fetchChildData()
        },
        afterSave: () => {
        },
        beforeDelete: () => {
          return true
        },
        afterDelete: () => {
        },
        beforeFlow: (valueTO, button) => {
          if (valueTO == 'submit' || (button && button.flagEnd)) {
            if (this.form.countDtl == 0) {
              this.utilMessage.error('入库单明细为空，不能提交')
              return false
            }

            if (!this.utils.isBaseTypeLom(this.form.purchaseOrderType)) {
              let rows = this.getDtlRef().getRows()
              // 校验效期
              let expData = rows.filter(row => {
                let expDate = new Date(row.expDate).getTime()
                let now = new Date().getTime()
                let diff = (expDate - now) / (24 * 60 * 60 * 1000)
                return diff < 180
              })
              if (expData.length > 0) {
                this.utilMessage.confirm('存在效期小于180天的,是否继续操作', () => {
                  this.propParent.handleViewFormFlow(button, null, true)
                })
                return false
              }

              // 校验批号
              // 校验效期
              expData = rows.filter(row => this.strings.isBlank(row.lot) || row.lot == '无')
              if (expData.length > 0) {
                this.utilMessage.confirm('存在无效的批号,是否继续操作', () => {
                  this.propParent.handleViewFormFlow(button, null, true)
                })
                return false
              }
            }

          }
          return true
        },
        afterFlow: valueTO => {
          if (valueTO == 'submit') {
            if (!that.utils.isBaseTypeLom(that.form.purchaseOrderType)) {
              // this.fetchChildData()
              this.$ajax.post('/wm/in_order/allowAutoAdjust', this.form).then(resp => {
                if (resp.data) {
                  this.utilMessage.confirm('该入库订单耗材价格和基础信息耗材表价格不一致,需要自动变更吗', () => {
                    that.autoChangeAdjust()
                  })
                }
              })
            }
          }
        },
        beforeClose: () => {
          return true
        },
        async afterClick(button, data, viewForm) {
          let {key: buttonKey} = button
          if (buttonKey == 'preview') {
            let param = {
              'that': that, //当前调用对象
              configList: [ //打印配置，可以多个
                {
                  //打印配置
                  printBusType: 'inOrder', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                  //主单据数据或者数据查询配置
                  formData: that.form, //数据对象
                  formDataId: that.form.id,
                }
              ]
            }
            global.utilPrint.openFormPrint(param)
          } else if (buttonKey == 'printsn') {
            global.utilPrint.openPrintLabel(null, that.form.busKey, null)
          } else if (buttonKey == 'toTransfer') {
            that.toTransfer()
          } else if (buttonKey == 'toPrepare') { // 转清点
            that.utilMessage.confirm('是否转清点单?', that.toPrepare)
          }
        }
      })
    },
    props: {
      propParent: Object,
      propInitData: Object,
      propPrimaryKey: String,
      propDictionaries: Object,
      propCurrentRow: Object,
      propViewFormData: Object,
      propReadonly: Boolean,
      propStatus: String,
      propRules: Object,
      propParam: Object,
      propFlowKey: String
    },
    components: {
      inOrderBarcode,
      barcodeParse,
      editUdi,
      customAnchor,
      customUpload,
      tableDrawerPackOperBag,
      dataImportArea,
      warehouseSelect,
      deptSelect,
      spSelect
    },
    methods: {
      //行编辑相关
      //行编辑耗材选择事件，在行编辑选择框选择后触发，根据选择的项来更新当前row的信息
      //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
      rowEditInput({row, column}) {
        if (column.property == 'packageQty') {
          // console.log('rowEditInput ', row)
          // console.log('this.utilNum.toFixed(column.model.value / row.skuQty)== ', this.utilNum.toFixed(column.model.value / row.skuQty))
          // if (!row.packageRate) { //如果没有换算比，先计算,column.model.value保存了原值
          //   this.$set(row, 'packageRate', this.utilNum.toFixed(column.model.value / row.skuQty))
          // }
          // let packageRate = this.utilNum.toFixed(row.amount) / row.skuPrice
          // this.$set(row, 'skuQty', this.utilNum.toFixed(packageRate * row.packageQty))
          // this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))

          this.$set(row, 'skuQty', this.utilNum.toFixed(row.packageRate * row.packageQty))
          this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
        }
        if (column.property == 'skuPrice') {
          this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
        }
      },
      //拆分明细
      splitOrderItem(row) {
        this.utilVue.loadShow(true)
        this.$ajax.post('/wm/in_order_item/splitOrderItem', row)
          .then(resp => {
            this.utilVue.loadHide()
            if (resp.success) {
              this.fetchChildData()
            }
          })
      },
      // 加载明细数据
      fetchChildData() {
        let queryWrapper = this.$newWrapper()
        if (this.form.id) {
          queryWrapper.eq('workOrderId', this.form.id)
        } else {
          queryWrapper.ne(1, 1)
        }
        this.getDtlRef().setQueryWrapper(queryWrapper)
      },
      afterLoad() {
      },

      getDtlRef() {
        if (this.cpHasMfgInfo) {
          return this.$refs.childDataView
        }
        return this.$refs.childDataViewNotMfg
      },

      // 二维码扫描
      qrCodeScan(scanValue) { //二维码扫描，要出现此功能必须先配置参数allowInternet为true(1)
        const params = {
          inOrderId: this.strings.isNotBlank(this.form.id) ? this.form.id : '',
          qrCode: scanValue,
          warehouseId: this.form.warehouseId,
          deliveryman: this.strings.isNotBlank(this.form.deliveryman) ? this.form.deliveryman : '',
          busUser: this.form.busUser
        }
        this.$ajax.post('/wm/in_order/scanQrCode', params).then(resp => {
          if (resp.success) {
            this.form = resp.data
            if (this.strings.isNotBlank(this.form.id) && this.form.id != '0') {
              this.utilMessage.success('扫码成功，请继续扫描其他子单信息！')
              this.fetchChildData()
            } else {
              this.$nextTick(() => {
                this.$emit('save')
              })
              this.utilMessage.success('主单扫码成功，请继续扫描子单信息！')
            }
          }
        })
      },
      // 仓库选择
      warehouseChange(row) {
        this.$set(this.form, 'warehouseId', row.id)
        this.$set(this.form, 'warehouseName', row.name)
      },
      // 供应商选择
      supplierChange(row) {
        this.$set(this.form, 'supplierId', row.id)
        this.$set(this.form, 'supplierName', row.name)
      },
      // 采购订单选择
      purchaseOrderSelect(row) {
        this.$set(this.form, 'supplierName', row.supplierName)
        this.$set(this.form, 'supplierId', row.supplierId)
        this.$set(this.form, 'flagOmoc', row.flagOmoc)
        this.$set(this.form, 'reagentTeamId', row.reagentTeamId || undefined)
        this.$set(this.form, 'purchaseOrderType', row.purchaseType)
        this.$set(this.form, 'flagConsignment', row.flagConsignment)
        this.$set(this.form, 'refId', row.id)
        this.$set(this.form, 'refKey', row.busKey)
        this.$set(this.form, 'purchaseOrderId', row.id)
        this.$set(this.form, 'deptId', row.deptIdDemand)
        this.$set(this.form, 'deptName', row.deptNameDemand)
      },

      // 扫描结果处理
      barCodeScanMain(scanValue) {
        if (this.form.warehouseId == null || this.form.warehouseId == 0) {
          this.utilMessage.error('请先选择仓库')
          return
        }
        if (!this.parameters.allowInternet()) { //二维码扫描
          this.qrCodeScan(scanValue)
          return
        }
        let codeType = barcodeParse.barCodeType(scanValue)
        if (codeType == 'ASN') { // 扫描的是送货单
          this.utilVue.loadShow(true)
          let that = this
          this.$ajax.get('/wm/in_order/get_delivery',
            {
              params: {
                asnKey: scanValue,
                warehouseId: this.form.warehouseId,
                deliveryman: this.form.deliveryman,
                busUser: this.form.busUser,
                busType : this.propParam.busType
              }
            }).then(async (resp) => {
            this.utilVue.loadHide()
            if (resp.code == 0) {
              that.propParent.ocUpdateViewForm(resp.data.workOrder)
            }
          })
          return
        }
        this.utilMessage.error(`扫码错误，格式不正确`)
      },

      // 主码扫描后
      scanInputMainAfterScan() {
        this.$refs.scanInputSub.focus()
      },

      // 恶人解析
      barCodeScanInputConfirm() {
        let valueMain = this.$refs.scanInputMain.getValue(false)
        let valueSub = this.$refs.scanInputSub.getValue(false)
        let scanValueAll = valueMain
        if (this.strings.isNotBlank(valueSub)) {
          scanValueAll+=valueSub
        }
        // scanValueAll = scanValueAll.replace(/\(/g,'')
        // scanValueAll = scanValueAll.replace(/\)/g,'')
        // 按照GTIN信息处理
        let scanInfo = barcodeParse.gtinAnalysis(scanValueAll)
        console.log(`barCodeScanInputConfirm   标签内容: ${scanValueAll} 解析结果:`, scanInfo)
        let wrapper = this.$newWrapper()
        let scanCode
        if (scanInfo.gtin) {
          scanCode = scanInfo.gtin
        } else if (scanInfo.udi) {
          scanCode = scanInfo.udi
        } else {
          this.utilMessage.warning('标签格式暂时不支持')
          return
        }
        wrapper.eq('gtin', scanCode).or('udi', scanCode)
        let params = {
          queryString: JSON.stringify(wrapper.queryConditions)
        }
        let that = this
        this.utilVue.loadShow(true)
        this.$ajax.get('/base/matr/list', {params}).then(resp => {
          this.utilVue.loadHide()
          if (resp.data.length > 1) {
            resp.data = resp.data.filter(tmp => !tmp.flagDisabled)
          }

          if (resp.data.length == 1) {
            that.scanConfirm = resp.data[0]
            if (this.strings.isNotBlank(this.form.supplierId) && this.scanConfirm.supplierId != this.form.supplierId) {
              this.utilMessage.warning('校验失败，该商品与主单据供应商不一致')
              return
            }
            if (this.strings.isNotBlank(this.form.flagOmoc) && this.scanConfirm.flagOmoc != this.form.flagOmoc) {
              this.utilMessage.warning('校验失败，该商品与主单据标签管理类型不一致')
              return
            }
            if (this.strings.isNotBlank(this.form.flagConsignment) && this.scanConfirm.flagConsignment != this.form.flagConsignment) {
              this.utilMessage.warning('校验失败，该商品与主单据寄售类型不一致')
              return
            }
            if (this.strings.isNotBlank(this.form.purchaseOrderType) && this.scanConfirm.baseType != this.form.purchaseOrderType) {
              this.utilMessage.warning('校验失败，该商品与主单据商品类型不一致')
              return
            }
            if (scanInfo.expiredDate) {
              that.$set(this.scanConfirm, 'expDate', scanInfo.expiredDate)
            }
            if (scanInfo.manufactureDate) {
              that.$set(this.scanConfirm, 'mfgDate', scanInfo.manufactureDate)
            }
            if (scanInfo.lot) {
              that.$set(this.scanConfirm, 'lot', scanInfo.lot)
            }
            if (scanInfo.sn) {
              that.$set(this.scanConfirm, 'mfgSn', scanInfo.sn)
            }
            this.scanConfirm.matrId = this.scanConfirm.id
            this.scanConfirm.matrSpec = this.scanConfirm.spec
            this.scanConfirm.matrName = this.scanConfirm.name
            this.scanConfirm.udi = scanValueAll
            this.scanConfirm.udiDi = scanInfo.udi
            this.$refs.customDrawerScan.show()
          } else if (resp.data.length > 1) {
            this.utilMessage.error(`编码【${scanCode}】找到${resp.data.length}个商品，请联系运营检查`)
          } else {
            this.utilMessage.error(`编码【${scanCode}】未找到对应的商品信息`)
          }
        })
      },

      // 调价
      autoChangeAdjust() {
        this.$ajax.post('/wm/in_order/workOderItemAdjust', this.form).then(resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.utils.refreshRefs(this)
            this.fetchChildData()
          }
        })
      },

      // 扩展按钮事件
      extraButtonClick({button, data, index}) {
        let buttonKey = button.key
        if (buttonKey === 'inOrderBarcode') { // 打印标签
          global.utilPrint.openPrintLabel(data.id, null, null)
        } else if (buttonKey === 'editUdi') { // 编辑UDI
          this.$refs.customDrawerUdi.show()
          this.$refs.editUdi.initData(data.id)
        } else if (buttonKey === 'packageInWarehouse') {
          this.utilMessage.info('跟台包入库请至手动入库进行操作')
        } else if (buttonKey === 'sgImportDtl') {
          //手工明细导入
          this.$refs.customDrawerSgImportDtl.show()
        }
      },

      cpAreaConfig() {
        return {
          name: 'box-1',
          title: '1、导入发货明细',
          help: `
            1、下载导入模板完善发货明细<br>
            2、导入发货明细
            `,
          downloadPath: `/wm/in_order_item/downloadExcelTemp/${this.form.id}`,
          importPath: `/wm/in_order_item/importDtl?deliveryId=${this.form.id}`
        }
      },

          // 导入成功
      importSuccess() {
        this.fetchChildData()
        // this.afterTableDataChange()
      },


      // 自定义选择聚焦回调
      customSelectFocus(column, row) {
        // 包装名称
        if (column.name == 'packageUnit') {
          if (this.strings.isBlank(row.matrId)) {
            this.utilMessage.warning('请先选择商品')
            return
          }
          this.utilSelect.matrUnit(this.packageUnitSelect, row.matrId)
        }
      },
      // 商品选择后
      matrSelect(rows, refName) {
        let rowFirst = rows[0]
        let matrAddList = rows.filter(
          item => item.matrId != rowFirst.matrId
            && item.matrBaseType == rowFirst.matrBaseType
            && item.flagOmoc == rowFirst.flagOmoc
            && item.flagConsignment == rowFirst.flagConsignment
            && item.supplierId == rowFirst.supplierId
        )
        matrAddList.push(rowFirst)
        if (rows.length != matrAddList.length) {
          this.utilMessage.confirm(`所选择的数据中，有${rows.length - matrAddList.length}条属性不一致，已忽略。是否提交?`, () => {
            //主单据未保存
            if(this.propParent.cpFormNew) {
              this.setFormByDtl(rowFirst)
              this.propParent.ocAsynSaveViewForm(() => {
                this.saveBatchItem(matrAddList, true)
              })
            }
          })
          return
        }
        //主单据未保存
        if(this.propParent.cpFormNew) {
          this.setFormByDtl(rowFirst)
          this.propParent.ocAsynSaveViewForm(() => {
            this.saveBatchItem(matrAddList)
          })
          return
        }
        this.saveBatchItem(matrAddList)
      },
      // 根据明细设置表单属性
      setFormByDtl(dtl) {
        console.log('dtl', dtl)
        if (dtl.matrBaseType) {
          this.$set(this.form, 'purchaseOrderType', dtl.matrBaseType)
        } else {
          this.$set(this.form, 'purchaseOrderType', dtl.baseType)
        }

        this.$set(this.form, 'flagOmoc', dtl.flagOmoc)
        this.$set(this.form, 'flagConsignment', dtl.flagConsignment)
        this.$set(this.form, 'supplierId', dtl.supplierId)
        this.$set(this.form, 'supplierName', dtl.supplierName)
      },
      saveBatchItem(rows) {
        this.utilVue.loadShow(true)
        rows.forEach(row => {
          row.workOrderId = this.form.id
          row.matrType = 0
          if (!row.baseType) {
            row.baseType = row.matrBaseType
          }
          if (!row.matrName) {
            row.matrName = row.name
          }
          if (!row.matrSpec) {
            row.matrSpec = row.spec
          }
          if (!row.matrModel) {
            row.matrModel = row.model
          }
        })
        this.$ajax.post('/wm/in_order/saveBatchForInOrder', rows).then((resp) => {
          this.utilVue.loadHide()
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.fetchChildData()
            this.utils.refreshRefs(this)

            if (this.$refs.scanInputSub) {
              this.$refs.scanInputSub.clear()
            }
            if (this.$refs.scanInputMain) {
              this.$refs.scanInputMain.clear()
            }
          }
        })
      },
      // 单位选择后
      packageUnitSelect(row, refName) {
        // 当前选中行
        let currentRow = this.getDtlRef().getCurrentRow()
        // 采购入库
        if (this.cpIsAsn) {
          //换算单位后是否为整数
          if (this.utilNum.isInt(currentRow.skuQty / row.rate)) {
            this.$set(currentRow, 'packageUnit', row.unit)
            this.$set(currentRow, 'packageRate', row.rate)
            this.$set(currentRow, 'packageQty', currentRow.skuQty / row.rate)
            this.$set(currentRow, 'amount', currentRow.skuPrice * currentRow.skuQty)
            return
          }
          this.utilMessage.confirm('该入库明细选择的包装不是整数,需要自动拆分吗', () => {
            this.$set(currentRow, 'packageUnit', row.unit)
            this.$set(currentRow, 'packageRate', row.rate)
            this.$set(currentRow, 'packageQty', currentRow.skuQty / row.rate)
            this.$set(currentRow, 'amount', currentRow.skuPrice * currentRow.skuQty)
            this.splitOrderItem(currentRow)
          })
        }
        //其他入库
        this.$set(currentRow, 'skuPrice', row.skuPrice)
        this.$set(currentRow, 'packageUnit', row.unit)
        this.$set(currentRow, 'packageRate', row.rate)
        this.$set(currentRow, 'skuQty', this.utilNum.toFixed(row.rate * currentRow.packageQty))
        this.$set(currentRow, 'amount', this.utilNum.toFixed(row.price * currentRow.packageQty))

      },
      // 转出库单
      toTransfer() {
        this.$set(this.dataConfirm, 'warehouseNameFrom', this.form.warehouseName)
        this.$set(this.dataConfirm, 'deptNameTo', this.form.deptName)
        this.$set(this.dataConfirm, 'deptIdTo', this.form.deptId)
        if (this.strings.isNotBlank(this.form.reagentTeamId)) {
          this.$set(this.dataConfirm, 'reagentTeamName', this.form.reagentTeamName)
          this.$set(this.dataConfirm, 'reagentTeamId', this.form.reagentTeamId)
        }

        this.$refs.customDrawerToTransfer.show()
      },
      // 转跟台备货
      toPrepare() {
        this.utilVue.loadShow(true)
        this.$ajax.post('/wm/oprt_check/toOprtCheck', this.form).then(resp => {
          this.utilVue.loadHide()
          if (resp.code == 0) {
            this.utils.refreshRefs(this)
            this.utilMessage.confirm('转换成功，是否打开该单据', () => {
              this.utils.refreshRefs(this)
              global.utils.openMenu('oprtcheck', {id: resp.data.id})
            }, () => {
            })
          }
        })
      },
      // 选择完需求科室
      deptChange(row) {
        this.$set(this.form, 'deptName', row.name)
        this.$set(this.form, 'deptId', row.id)
      },
      // 选择完收货科室
      deptNameToSelect(row) {
        this.$set(this.dataConfirm, 'deptNameTo', row.name)
        this.$set(this.dataConfirm, 'deptIdTo', row.id)
        this.$set(this.dataConfirm, 'reagentTeamName', '')
        this.$set(this.dataConfirm, 'reagentTeamId', '')
      },
      // 转出库单确认
      customDrawerToTransferConfirm() {
        this.$refs.dataConfirm.validate().then(result => {
          if (result) {
            this.utilVue.loadShow(true)
            this.form.deptIdTo = this.dataConfirm.deptIdTo
            this.form.reagentTeamId = this.dataConfirm.reagentTeamId
            this.$ajax.post('/wm/transfer/autoChangeTransfer', this.form).then(resp => {
              this.utilVue.loadHide()
              if (resp.code == 0) {
                this.utilMessage.confirm('转换成功，是否打开该单据', () => {
                  this.utils.refreshRefs(this)
                  global.utils.openMenu('transfer', {id: resp.data.id})
                }, () => {
                  this.utils.refreshRefs(this)
                })
              }
            })
          }
        })
      },

      // 过滤显示按钮
      propFilterBtn(btnList) {
        // 包选择只在跟台入库显示
        // if (!this.cpIsPackage || this.propReadonly) {
        //   btnList =  btnList.filter(btn => !['selectPack'].includes(btn.code))
        // }
        // 采购入库时，不要明细的添加按钮
        if (this.cpIsAsn || this.cpIsPackage) {
          return btnList.filter(btn => !['vb-add', 'selectPack'].includes(btn.code))
        }
        return btnList
      },

      // 过滤编辑列
      propIsColumnEdit(column) {
        // 跟台入库时，除了包装数量、批次、效期、生产日期、灭菌日期、灭菌效期、灭菌类型其他的都不可以编辑
        if (this.cpIsPackage && !['packageQty','lot','expDate','mfgDate','sterilizationDate','sterilizationIndate'].includes(column.name)) {
          return false
        }

        // 采购入库时，除了包装单位、其他的都不可以编辑
        if (this.cpIsAsn && !['packageUnit'].includes(column.name)) {
          return false
        }

        // 其他入库
        if (['matrName', 'packageUnit', 'packageQty', 'lot', 'expDate','mfgDate', 'mfgSn', 'sterilizationDate','sterilizationIndate'].includes(column.name)) {
          return true
        }
        return false
      },

      // UDI扫描结果确认
      customDrawerScanConfirm() {
        this.matrSelect([this.scanConfirm])
      },
      // 列表添加按钮
      propBeforeClickDtl(button, formData , rowData, that) {
        //列表添加按钮 跟台入库
        if (button.key == 'selectPack') {
          this.$refs.tableDrawerPackOperBag.show()
          return false;
        }
        //列表添加按钮 其他入库
        if (button.key == 'vb-add') {
          let supplierId = ''
          if (!this.cpIsInit) {
            supplierId = this.form.supplierId
          }
          this.utilSelect.matrMore(
            this.matrSelect,
            null ,
            supplierId,
            this.form.purchaseOrderType,
            this.form.flagConsignment,
            this.form.flagOmoc
          )
          return false
        }


        return true;
      },

      // 模板选择后
      packSelect(rows, formData) {
        this.utilVue.loadShow(true)

        let params = {
          workOrderId: this.form.id,
          locationId: this.form.warehouseId,
          locationName: this.form.warehouseName,
          lot: formData.lot,
          expDate: formData.expDate,
          mfgDate: formData.mfgDate,
          sterilizationDate: formData.sterilizationDate,
          sterilizationIndate: formData.sterilizationIndate,
          packTemplets: rows
        }
        this.$ajax.post('/wm/in_order_item/addByPackTemp', params).then(resp => {
          this.utilVue.loadHide()
          if (resp.code == 0) {
            this.formPack = {}
            this.$refs.tableDrawerPackOperBag.hide()
            this.utilMessage.success(resp.msg)
            this.fetchChildData()
            this.utils.refreshRefs(this)
          }
        })
      },
      // 单元格输入校验
      rowEditInputValid(row, column,field, value) {
        if (field == 'skuPrice' && value <= 0 ) {
          this.utilMessage.warning('单价应该大于0')
          return false
        }
        return true
      }
    }
  }
</script>
